import time

from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By


class Base:
    def __init__(self, driver: WebDriver = None):
        if driver is None:
            self.options = webdriver.ChromeOptions()
            self.options.add_argument('--headless')  # 增加无界面选项
            self.options.add_argument('--disable-gpu')  # 如果不加这个选项，有时定位会出现问题
            self.options.add_argument('--no-sandbox')  # 使用root权限运行
            self.options.add_argument('--disable-software-rasterizer')
            self.driver = webdriver.Chrome(options=self.options)
            self.driver.get('http://10.1.201.231')
            self.driver.set_window_position(1366, 0)
            self.driver.maximize_window()
            self.driver.implicitly_wait(5)

        else:
            self.driver = driver

    # 查找元素

    def find(self, by, loc):
        return WebDriverWait(self.driver, timeout=30).until(lambda x: self.driver.find_element(by, loc))

    # 点击方法

    def click(self, by, loc):
        return self.find(by, loc).click()

    # 输入方法
    def input(self, by, loc, v):
        return self.find(by, loc).send_keys(v)

    # 获取文本信息

    def text(self, by, loc):
        return self.find(by, loc).text

    # 截图方法
    def base_get_image(self):
        self.driver.get_screenshot_as_file('../image/{}.png'.format(time.strftime("%Y_%m_%d_%H_%M_%S")))

    # 判断元素是否存在

    def base_element_is_exist(self, loc):
        try:
            self.find(loc)
            print("元素存在...")
            return True
        except:
            print("元素不存在...")
            return False

    # 关闭浏览器
    def close_brower(self):
        self.driver.close()
